package com.bw;

import com.bw.pojo.*;
import com.bw.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@CrossOrigin //跨域
@RestController
@Slf4j
public class OrderController {

    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private OrderDetailRepository repository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UpdateStockService service;
    @Autowired
    private EmailService emailService;

    @RequestMapping("/listCourse")
    public List<Course> listCourse(){
        List<Course> list=courseRepository.findAll();
        return list;
    }

    @PostMapping("/creteOrder")
    public boolean creteOrder(@RequestBody List<OrderDetailDTO> ods){
        //订单总金额
        BigDecimal total = new BigDecimal(0);
        Order order = new Order();
        List<OrderDetail> details = new ArrayList<>();
       ods.forEach(dto -> {
           Optional<Course> optional = courseRepository.findById(dto.getId());
           Course course=optional.get();
           OrderDetail orderDetail = new OrderDetail(dto.getPrice(),dto.getQty(),order,course);

           BigDecimal amount = dto.getPrice().multiply(BigDecimal.valueOf(dto.getQty()));
           BigDecimal currentTotal = order.getSum().add(amount);
           order.setSum(currentTotal);
           order.setUid(1);
           details.add(orderDetail);
            //库存扣除
           boolean success = service.updateStock(dto.getId(),dto.getQty());
            if (!success){
                log.debug("产品"+dto.getId()+"库存扣除"+dto.getQty()+"个失败");
           }
       });
       repository.saveAll(details);
       List<User> all = userRepository.findAll();
       String [] user = new String[all.size()];
       for (int i = 0; i <all.size(); i++) {
            user[i]= all.get(i).getEmail();
        }
       Course course = new Course();
       return emailService.shop(course,user);
    }

    @PostMapping("/login")
    public User login(@RequestBody User user){
        return userRepository.save(user);
    }
}
